package com.buli.blmall.admin.utils;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import com.buli.blmall.admin.common.domain.WxMessage;
import org.apache.commons.lang3.StringUtils;

/**
 * @author https://www.wdbyte.com
 */
public class WeixinMsgUtil {

    // 事件-关注
    private static String EVENT_SUBSCRIBE = "subscribe";

    /**
     * 微信消息转对象
     *
     * @param xml
     * @return
     */
    public static WxMessage msgToReceiveMessage(String xml) {
        JSONObject jsonObject = JSON.parseObject(WeixinUtil.xml2json(xml));
        WxMessage wxMessage = new WxMessage();
        wxMessage.setToUserName(jsonObject.getString("ToUserName"));
        wxMessage.setFromUserName(jsonObject.getString("FromUserName"));
        wxMessage.setCreateTime(jsonObject.getString("CreateTime"));
        wxMessage.setMsgType(jsonObject.getString("MsgType"));
        wxMessage.setContent(jsonObject.getString("Content"));
        wxMessage.setMsgId(jsonObject.getString("MsgId"));
        wxMessage.setEvent(jsonObject.getString("Event"));
        wxMessage.setTicket(jsonObject.getString("Ticket"));
        return wxMessage;
    }

    /**
     * 是否是订阅事件
     *
     * @param wxMessage
     * @return
     */
    public static boolean isEventAndSubscribe(WxMessage wxMessage) {
        return StringUtils.equals(wxMessage.getEvent(), EVENT_SUBSCRIBE);
    }

    /**
     * 是否是二维码扫描事件
     *
     * @param wxMessage
     * @return
     */
    public static boolean isScanQrCode(WxMessage wxMessage) {
        return StringUtils.isNotEmpty(wxMessage.getTicket());
    }

    /**
     * 获取扫描的二维码 Ticket
     *
     * @param wxMessage
     * @return
     */
    public static String getQrCodeTicket(WxMessage wxMessage) {
        return wxMessage.getTicket();
    }

}